package com.ityuwen.mengyagushi.live.config;

import com.ityuwen.mengyagushi.common.constant.RedisConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.lang.Nullable;

@Configuration
public class RedisListenerConfig {

    @Autowired
    private RedisTemplate redisTemplate;

    @Bean
    public RedisMessageListenerContainer listenerContainer(RedisConnectionFactory connectionFactory){

        RedisMessageListenerContainer listenerContainer = new RedisMessageListenerContainer();
        listenerContainer.setConnectionFactory(connectionFactory); // 连接工厂
        listenerContainer.addMessageListener((Message message, @Nullable byte[] pattern) -> {
            System.out.println("信道：" + new String(message.getChannel()));
            String msg = redisTemplate.getValueSerializer().deserialize(message.getBody()).toString();

            ChartRoomContainer.sendMsg(msg);

        }, new ChannelTopic(RedisConstant.LIVE_CHAT_CHANNEL));
        return listenerContainer;
    }
}
